from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from dynamic_scraper.models import Scraper, SchedulerRuntime
from scrapy.contrib.djangoitem import DjangoItem


class MotorSite(models.Model):
    name = models.CharField(max_length=200)
    domain = models.CharField(max_length=64)
    url = models.URLField()
    scraper = models.ForeignKey(Scraper, blank=True, null=True, on_delete=models.SET_NULL)
    scraper_runtime = models.ForeignKey(SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL)

    def __unicode__(self):
        return self.name


class MotorSubSiteManager(models.Manager):
    pass


class MotorSubSite(models.Model):
    name = models.CharField(max_length=200)
    motor_site = models.ForeignKey(MotorSite, name='source')
    logo = models.URLField()
    url = models.URLField()
    scraper = models.ForeignKey(Scraper, blank=True, null=True, on_delete=models.SET_NULL)
    scraper_runtime = models.ForeignKey(SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL)
    created_at = models.DateTimeField(auto_now_add=True)
    # last_processed = models.DateTimeField(auto_now=True, auto_now_add=True)
    # last_cost = models.TimeField(null=False, default=0)

    objects = MotorSubSiteManager()

    def __unicode__(self):
        return self.name


class MotorSubSiteItem(DjangoItem):
    django_model = MotorSubSite


class CarManager(models.Manager):
    pass


class Car(models.Model):
    name = models.CharField(max_length=200)
    motor_subsite = models.ForeignKey(MotorSubSite, name='source')
    car_desc = models.TextField(blank=True)
    url = models.URLField()
    checker_runtime = models.ForeignKey(SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL)

    objects = CarManager()

    def __unicode__(self):
        return self.name


class CarItem(DjangoItem):
    django_model = Car


@receiver(pre_delete)
def pre_delete_handler(sender, instance, using, **kwargs):
    if isinstance(instance, Car) and instance.checker_runtime:
        instance.checker_runtime.delete()

pre_delete.connect(pre_delete_handler)
